<template>
  <div class="wrapper" style="padding-top: 8px">
    <el-form ref='userDetail' :model="userDetail" :rules="userDetailRules" label-width="120px" v-loading="loading">
      <el-row>
        <el-col :span="6">
          <!-- 头像 -->
          <!--suppress HtmlUnknownTarget -->
          <el-avatar class="avatar" :size="72" :src='userDetail.headImg' title='点击更改头像'/>
        </el-col>
        <el-col :span="6">
          <!-- 只读用户id -->
          <el-input :disabled="true" v-model="userDetail.accountId" class="input"/>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="nickname" label="昵称" class="input" label-width="100px">
            <el-input v-model="userDetail.nickname" placeholder="昵称" :maxlength="12"/>
          </el-form-item>
        </el-col>
        <el-col :span='12'>
          <el-form-item prop="firstName" label="姓" class="input">
            <el-input v-model="userDetail.firstName" placeholder="姓" :maxlength="12" />
          </el-form-item>
        </el-col>
        <el-col :span='12'>
          <el-form-item prop="lastName" label="名" class="input" label-width="100px">
            <el-input v-model="userDetail.lastName" placeholder="名" :maxlength="12"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item prop="birthday" label="生日" >
        <el-date-picker type="date" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
                        v-model="userDetail.birthday" placeholder="生日" :picker-options="pickerOptions"
                        style="width: 100%" />
      </el-form-item>
      <el-form-item prop="idNumber" label="身份证号" class="input">
        <el-input v-model="userDetail.idNumber" placeholder="身份证号" maxlength="18"/>
      </el-form-item>
      <el-form-item prop="qq" label="QQ" class="input">
        <el-input v-model="userDetail.qq" placeholder="QQ" :maxlength="14"/>
      </el-form-item>
      <el-form-item prop="phone" label="手机号码" class="input">
        <el-input v-model="userDetail.phone" placeholder="Phone Number" :maxlength="11"/>
      </el-form-item>
      <el-form-item prop="email" label="邮箱地址" class="input">
        <el-input v-model="userDetail.email" placeholder="Email" :maxlength="24"/>
      </el-form-item>
      <el-form-item prop="weChat" label="微信账号" class="input">
        <el-input v-model="userDetail.weChat" placeholder="We Chat" :maxlength="24"/>
      </el-form-item>
      <el-row :span='24' style="text-align: left">
        <xum-button class="btn" type="primary" @click="submitUser('userDetail')"
          :disabled="submitUserLoading" :loading="submitUserLoading">提交信息</xum-button>
      </el-row>
    </el-form>
    <el-row :span='24' style="text-align: left">
      <h5 class="title">修改密码</h5>
    </el-row>
    <el-form :model="password" ref="password" :rules="passwordRules" label-width="120px">
      <el-form-item prop="oldPass" label="原密码" class="input">
        <el-input placeholder="原密码" type="password" v-model="password.oldPass" :maxlength="32"/>
      </el-form-item>
      <el-form-item prop="newPass" label="新密码" class="input">
        <el-input placeholder="新密码" type="password" v-model="password.newPass" :maxlength="32"/>
      </el-form-item>
      <el-form-item prop="newPassCheck" label="确认密码" class="input">
        <el-input placeholder="确认密码" type="password" v-model="password.newPassCheck" :maxlength="32"/>
      </el-form-item>
      <el-form-item prop="imageCode" label="验证码" class="input">
        <el-input type="imageCode" :maxlength="6" v-model="password.imageCode" placeholder="请输入图片验证码">
          <!--suppress HtmlUnknownTarget -->
          <img class="imageCode" alt="imageCode" slot="append" :src="imageCodeUrl" @click="freshImageCode"/>
        </el-input>
      </el-form-item>
      <el-row :span='24' style="text-align: left">
        <xum-button class="btn" type="primary" @click="submitPassword('password')"
          :disabled="submitPassLoading" :loading="submitPassLoading">更改密码</xum-button>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import XumButton from '@/components/general/XumButton'
import userInfoController, { updateCurrentUserInfo } from '@/api/ApiUserInfo'
import { ResultCode } from '@/constants/constants'
import UserInfoChgDTO from '@/api/entity/UserInfoChgDTO'
import { changePassByPass } from '@/api/ApiUser'
import sysConfig from '@/config/sysConfig'

export default {
  name: 'AccountDetail',
  components: {
    'xum-button': XumButton
  },
  data () {
    const validPassword1 = (rule, value, callback) => {
      this.$refs.password.validateField('newPassCheck')
      callback()
    }
    const validPassword2 = (rule, value, callback) => {
      if (!value) {
        callback()
      }
      if (this.password.newPass !== value) {
        callback(new Error('密码不一致'))
      }
      return callback()
    }
    const birthdayValid = (rule, value, callback) => {
      if (value) {
        const date = new Date(value)
        if (date > new Date()) {
          callback(new Error('出生日期不能大于当前日期'))
        }
        if (date < new Date('1900-01-01')) {
          callback(new Error('出生日期不能小于1900年1月1日'))
        }
        callback()
      }
      callback()
    }
    return {
      loading: true,
      submitUserLoading: false,
      submitPassLoading: false,
      defaultHeadImage: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1575266770070&di=50d9da00e429a929c92ae09e3f784d2c&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201902%2F13%2F20190213130110_xTPxP.thumb.700_0.jpeg',
      userDetail: {
        accountId: '',
        firstName: '',
        lastName: '',
        nickname: '',
        headImg: '',
        birthday: '',
        idNumber: '',
        qq: '',
        phone: '',
        email: '',
        weChat: ''
      },
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      userDetailRules: {
        firstName: [
          { min: 0, max: 12, message: '长度在 0 到 12 个字符', trigger: 'blur' }
        ],
        lastName: [
          { min: 0, max: 12, message: '长度在 0 到 12 个字符', trigger: 'blur' }
        ],
        nickname: [
          { min: 0, max: 12, message: '长度在 0 到 12 个字符', trigger: 'blur' }
        ],
        birthday: [
          { validator: birthdayValid, trigger: 'blur' }
        ],
        idNumber: [
          {
            pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
            message: '不是合格的身份证号',
            trigger: 'blur'
          }
        ],
        qq: [
          { min: 5, max: 14, message: 'QQ号为收尾不为0的4-14位数字', trigger: 'blur' },
          { pattern: /^[1-9]\d{4,13}$/, message: '不是合格的qq账号', trigger: 'blur' }
        ],
        phone: [
          { min: 11, message: '手机号码为11位数字', trigger: 'blur' },
          { pattern: /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/, message: '不是合格的手机号码', trigger: 'blur' }
        ],
        email: [
          {
            pattern: /^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$/,
            message: '不是一个合格的邮箱地址',
            trigger: 'blur'
          }
        ],
        weChat: [

        ]
      },
      password: {
        oldPass: '',
        newPass: '',
        newPassCheck: '',
        imageCode: ''
      },
      imageCodeFresh: new Date().getTime(),
      passwordRules: {
        oldPass: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 32, message: '长度在 3 到 32 个字符', trigger: 'blur' }
        ],
        newPass: [
          { required: true, message: '请设置密码', trigger: 'blur' },
          { min: 3, max: 32, message: '密码长度在 3 到 32 个字符', trigger: 'blur' },
          { validator: validPassword1, trigger: 'blur' }
        ],
        newPassCheck: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { min: 3, max: 32, message: '密码长度在 3 到 32 个字符', trigger: 'blur' },
          { validator: validPassword2, trigger: 'blur' }
        ],
        imageCode: [
          { required: true, message: '验证码不能为空', trigger: 'blur' },
          { pattern: '^[0-9a-zA-Z]{4,6}$', message: '验证码是4-6个数字或字母组成的字符串', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    /**
     * 更改用户基本信息
     */
    submitUser (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.submitUserLoading = true
          const userInfoChgDTO = UserInfoChgDTO.instance()
            .setNickname(this.userDetail.nickname || undefined)
            .setEmail(this.userDetail.email || undefined)
            .setBirthday(this.userDetail.birthday || undefined)
            .setFirstName(this.userDetail.firstName || undefined)
            .setIdNumber(this.userDetail.idNumber || undefined)
            .setLastName(this.userDetail.lastName || undefined)
            .setPhone(this.userDetail.phone || undefined)
            .setQq(this.userDetail.qq || undefined)
            .setWeChat(this.userDetail.weChat || undefined)
          updateCurrentUserInfo(userInfoChgDTO, () => {
            this.refreshAccountInfo(() => {
              this.$message.success('更新数据成功')
            })
          }, () => {
            this.submitUserLoading = false
          })
        }
      })
    },
    /**
     * 更改用户密码
     */
    submitPassword (formName) {
      const vm = this
      this.$refs[formName].validate(valid => {
        if (valid) {
          vm.submitPassLoading = true
          changePassByPass(vm.password.oldPass, vm.password.newPass, vm.password.imageCode, () => {
            vm.$message.success('更改密码成功')
          }, () => {
            vm.submitPassLoading = false
          })
        }
      })
    },
    /**
     * 更新用户基本信息
     * @param success 更新成功回调，在更新数据后刷新数据需要用到
     */
    refreshAccountInfo (success = null) {
      const vm = this
      vm.loading = true
      userInfoController.queryCurrentUserInfo(data => {
        if (data.code === ResultCode.OK) {
          data = data.object
          if (data) {
            vm.userDetail.accountId = data.accountId || ''
            vm.userDetail.birthday = data.birthday
              ? (data.birthday[0] + '-' +
              (data.birthday[1] < 10 ? '0' : '') + data.birthday[1] + '-' +
              (data.birthday[2] < 10 ? '0' : '') + data.birthday[2]) : ''
            vm.userDetail.headImg = data.headImg || vm.defaultHeadImage
            vm.userDetail.idNumber = data.idNumber || ''
            vm.userDetail.firstName = data.firstName || ''
            vm.userDetail.lastName = data.lastName || ''
            vm.userDetail.nickname = data.nickname || ''
            vm.userDetail.phone = data.phone || ''
            vm.userDetail.qq = data.qq || ''
            vm.userDetail.weChat = data.weChat || ''
          }
          if (success !== null) {
            success(data)
          }
        }
      }, () => {
        vm.loading = false
      })
    },
    /**
     * 更新图片验证码
     */
    freshImageCode () {
      this.imageCodeFresh = new Date().getTime()
    }
  },
  computed: {
    imageCodeUrl () {
      return sysConfig.baseUrl + '/middle-user/user/imageCode?key=changePass&temp=' + this.imageCodeFresh + ')'
    }
  },
  mounted () {
    this.refreshAccountInfo()
  }
}
</script>

<style lang="scss" scoped>
  .wrapper{

    padding: 0 32px;

    .avatar{
      cursor: pointer;
      position: relative;
      user-select: none;
    }

    .title{
      margin-left: 120px;
      user-select: none;
      font-family: 'Roboto Condensed', sans-serif;
      color: #333333;
      font-size: 16px;
      margin-top: 24px;
    }

    .input{
      margin-top: 18px;
    }

    .btn{
      margin-left:120px;
    }

    .imageCode{
      cursor: pointer;
      width: 80px;
      height: 32px;
      min-height: 100%;
      display: inline-block;
      background-size: 100% 100%;
    }

  }
</style>
